﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DevExpress.Web.Mvc;
using ElingOA6_Admin_DSJCJ.Common;
using System.Data;
using System.Text;
using Newtonsoft.Json;
using ElingOA6_Admin_DSJCJ.Areas.Admin.Models;

namespace ElingOA6_Admin_DSJCJ.Areas.Admin.Controllers
{
    [OutputCache(Duration = 0, VaryByParam = "none")]
    public class OfficeItemUseAppayController : Common.AdminBaseController
    {
        //
        // GET: /Admin/OfficeItemUseAppay/
        [AuthorityActionFilter("m_OfficeItemUseApply", Order = 1)]
        [LogPageActionFilter("物品领用管理", Order = 2)]
        public ActionResult Index()
        {
            string strwhere = " FInsEmplNo ='" + OperateSession.get(Common.GlobalConstant.PARAM_FEMPLNO) + "' and (FStatus='N' or FStatus='B')";
            List<Model.ItemRequisitionApply> ItemRequisitionApplyList = GetItemRequisitionApplyList(strwhere, 1);
            return View(ItemRequisitionApplyList);
        }

        public ActionResult OfficeItemUseAppayListPartial()
        {
            int pageIndex = Request.Params["pageIndex"] == null ? 0 : int.Parse(Request.Params["pageIndex"].ToString());
            int pageCount = Request.Params["PageCount"] == null ? 0 : int.Parse(Request.Params["PageCount"].ToString());
            int pageRowSize = Request.Params["pageRowSize"] == null ? 0 : int.Parse(Request.Params["pageRowSize"].ToString());
            int pageRowCount = Request.Params["pageRowCount"] == null ? 0 : int.Parse(Request.Params["pageRowCount"].ToString());
            string callbackArg = DevExpressHelper.CallbackArgument;
            string command = Request.Params["command"] == null ? "" : Request.Params["command"].ToString();

            if (command == "PAGERONCLICK")
            {
                string[] args = callbackArg.Split(new char[1] { '|' });
                string arg = args[args.Count() - 1];

                switch (arg)
                {
                    case "PBN;":
                        {
                            //下一页
                            pageIndex = pageIndex + 2;
                            break;
                        }
                    case "PBP;":
                        {
                            //上一页
                            //pageIndex = pageIndex;
                            break;
                        }
                    case "PBL;":
                        {
                            //最后一页
                            pageIndex = pageCount;
                            break;
                        }
                    case "PBF;":
                        {
                            //第一页
                            pageIndex = 1;
                            break;
                        }
                    default:
                        {
                            //点击数字页码
                            string tempIndex = arg.Replace("PN", "");
                            tempIndex = tempIndex.Replace(";", "");
                            if (RegExp.IsNumeric(tempIndex))
                            {
                                pageIndex = int.Parse(tempIndex) + 1;
                            }
                            break;
                        }

                }
            }
            else
            {
                pageIndex = pageIndex + 1;
            }
            string strwhere = " FInsEmplNo ='" + OperateSession.get(Common.GlobalConstant.PARAM_FEMPLNO) + "' and (FStatus='N' or FStatus='B')";
            List<Model.ItemRequisitionApply> ItemRequisitionApplyList = GetItemRequisitionApplyList(strwhere, pageIndex);
            return PartialView("OfficeItemUseAppayListPartial", ItemRequisitionApplyList);
        }

        /// <summary>
        /// 获取定义的工作时间数据
        /// </summary>
        /// <param name="strWhere">查询条件</param>
        /// <param name="pageIndex">第几页</param>
        /// <returns>查询出来的数据</returns>
        private List<Model.ItemRequisitionApply> GetItemRequisitionApplyList(string strWhere, int pageIndex)
        {
            BLL.Common commonBll = new BLL.Common();
            BLL.ItemRequisitionApply ItemRequisitionApplyBLL = new BLL.ItemRequisitionApply();
            string fiedls = "*";
            int total;
            DataSet ds = commonBll.GetListByPage("v_ItemRequisitionApply", fiedls, Common.GlobalConstant.CONSTRING_PAGESIZE, pageIndex, strWhere, "FApplyDate", 1, out total);
            List<ElingOA6_Admin_DSJCJ.Model.ItemRequisitionApply> itemRequisitionApplyList = ItemRequisitionApplyBLL.DataTableToList(ds.Tables[0]);
            List<Model.ItemRequisitionApply> itemRequisitionApplyAllList = new List<Model.ItemRequisitionApply>();

            int pageRowSize = Common.GlobalConstant.CONSTRING_PAGESIZE;
            for (int i = 0; i < total; i++)
            {
                itemRequisitionApplyAllList.Add(null);
            }
            for (int i = 0; i < pageRowSize; i++)
            {
                if (itemRequisitionApplyList.Count > i)
                {
                    itemRequisitionApplyAllList[((pageIndex - 1) * pageRowSize) + i] = itemRequisitionApplyList[i];
                }
            }

            return itemRequisitionApplyAllList;
        }

        public List<Model.ItemRequisitionApplyEntry> GetShowList(List<Model.ItemRequisitionApplyEntry> list)
        {
            if (list.Count > 0)
            {
                string nolist = "";
                foreach (Model.ItemRequisitionApplyEntry model in list)
                {
                    if (nolist != "")
                    {
                        nolist += "," + model.FItemNo;
                    }
                    else
                    {
                        nolist += model.FItemNo;
                    }
                }

                BLL.Item ItemBLL = new BLL.Item();
                List<Model.Item> ItemList = ItemBLL.GetListAll("FItemNo in (" + nolist + ")");

                foreach (Model.ItemRequisitionApplyEntry model in list)
                {
                    List<Model.Item> selectItemList = (from nm in ItemList where nm.FItemNo == model.FItemNo select nm).ToList();
                    model.FItemName = selectItemList[0].FItemName;
                    model.FPrice = selectItemList[0].FPrice;
                    model.FQcQty = selectItemList[0].FQty.ToString();
                }
            }
            return list;
        }

        public ActionResult OfficeItemUseAppayEdit(string fNo)
        {
           
            Model.ItemRequisitionApply itemRequisitionApplyModel = new Model.ItemRequisitionApply();
            int z = 0;
            if (fNo != null && fNo != "")
            {
                BLL.ItemRequisitionApply itemRequisitionApplyBLL = new BLL.ItemRequisitionApply();
                itemRequisitionApplyModel = itemRequisitionApplyBLL.GetModel(int.Parse(fNo));
                BLL.ItemRequisitionApplyEntry itemRequisitionApplyEntryBLL = new BLL.ItemRequisitionApplyEntry();
                List<Model.ItemRequisitionApplyEntry> itemRequisitionApplyEntryList = itemRequisitionApplyEntryBLL.GetModelList("FItemRequisitionApplyID=" + fNo + "");
                
                
                BLL.HREmpl HREmplBLL = new BLL.HREmpl();
                string str = HREmplBLL.GetEmpNameAndDept(Common.GlobalConstant.ENTITYNO, itemRequisitionApplyModel.FApplyEmplNo);

                SelectEmpModel empModel = JsonConvert.DeserializeObject<SelectEmpModel>(str);

                itemRequisitionApplyModel.FApplyEmplName = empModel.FEmpName;
                itemRequisitionApplyModel.FApplyDeptName = empModel.FDeptName;

                ViewData["ShowList"] = GetTable(GetShowList(itemRequisitionApplyEntryList), ref z);
                ViewData["selectIndex"] = z;
                ViewData["fItemRequisitionApplyID"] = fNo;
                ViewData["type"] = "Edit";
            }
            else
            {
                itemRequisitionApplyModel.FInsEmplNo = Common.OperateSession.get(Common.GlobalConstant.PARAM_LOGINID);
                ViewData["ShowList"] = "";
                ViewData["selectIndex"] = z;
                ViewData["type"] = "Add";
            }
            return View(itemRequisitionApplyModel);
        }

        public string QueryEmp(string no)
        {
            try
            {
                BLL.HREmpl HREmplBLL = new BLL.HREmpl();
                string str = HREmplBLL.GetEmpNameAndDept(Common.GlobalConstant.ENTITYNO, no);
                return str;
            }
            catch
            {
                return "";
            }
        }

        public ActionResult Save(Model.ItemRequisitionApply itemRequisitionApplyModel)
        {
            List<Model.ItemRequisitionApplyEntry> ItemRequisitionApplyEntryList = new List<Model.ItemRequisitionApplyEntry>();
            try
            {
                itemRequisitionApplyModel.FStatus = "N";
                string[] fItemNos = Fetch.Post("FItemNo").Split(',');
                string[] fQtys = Fetch.Post("FQty").Split(',');

               
                for (int i = 0; i < fItemNos.Count(); i++)
                {
                    Model.ItemRequisitionApplyEntry ItemRequisitionApplyEntryModel = new Model.ItemRequisitionApplyEntry();
                    ItemRequisitionApplyEntryModel.FApplyQty = fQtys[i];
                    ItemRequisitionApplyEntryModel.FEntityNo = Common.GlobalConstant.ENTITYNO;
                    ItemRequisitionApplyEntryModel.FItemNo = fItemNos[i];
                    ItemRequisitionApplyEntryList.Add(ItemRequisitionApplyEntryModel);
                }

                itemRequisitionApplyModel.FEntityNo = Common.GlobalConstant.ENTITYNO;
                itemRequisitionApplyModel.FApplyDeptNo = Fetch.Post("hdFApplyDeptNo");
                itemRequisitionApplyModel.FApplyEmplNo = Fetch.Post("hdFApplyEmplNo");
                BLL.ItemRequisitionApply ItemRequisitionApplyBLL = new BLL.ItemRequisitionApply();

                if (Fetch.Post("hdtype") == "Add")
                {
                    itemRequisitionApplyModel.FApplyIP = Common.GenerateUtil.GetClientIPv4Address();
                    itemRequisitionApplyModel.FApplyDate = DateTime.Now;
                    itemRequisitionApplyModel.FInsEmplNo = OperateSession.get(Common.GlobalConstant.PARAM_FEMPLNO);
                    ItemRequisitionApplyBLL.Add(itemRequisitionApplyModel, ItemRequisitionApplyEntryList);
                }
                else
                {
                    itemRequisitionApplyModel.FUpdIP = Common.GenerateUtil.GetClientIPv4Address();
                    itemRequisitionApplyModel.FUpdDate = DateTime.Now;
                    itemRequisitionApplyModel.FUpdEmplNo = OperateSession.get(Common.GlobalConstant.PARAM_FEMPLNO);

                    itemRequisitionApplyModel.FItemRequisitionApplyID = int.Parse(Fetch.Post("hdfItemRequisitionApplyID"));
                    ItemRequisitionApplyBLL.Update(itemRequisitionApplyModel, ItemRequisitionApplyEntryList);
                }
                ViewData["jsAlert"] = "操作成功";
            }
            catch
            {
                ViewData["jsAlert"] = "操作失败";
            }
            BLL.ItemRequisitionApply itemRequisitionApplyBLL = new BLL.ItemRequisitionApply();
            int z = 0;
            BLL.ItemRequisitionApplyEntry itemRequisitionApplyEntryBLL = new BLL.ItemRequisitionApplyEntry();
            ViewData["ShowList"] = GetTable(GetShowList(ItemRequisitionApplyEntryList), ref z);
            ViewData["selectIndex"] = z;
            ViewData["fItemRequisitionApplyID"] = itemRequisitionApplyModel.FItemRequisitionApplyID;
            ViewData["type"] = Fetch.Post("hdtype");
            return View("OfficeItemUseAppayEdit", itemRequisitionApplyModel);
        }

        public string GetTable(List<Model.ItemRequisitionApplyEntry> ItemRequisitionApplyEntryList, ref int z)
        {
            StringBuilder str = new StringBuilder();
            foreach (Model.ItemRequisitionApplyEntry model in ItemRequisitionApplyEntryList)
            {
                z++;
                str.Append("<tr id='" + z + "'>");
                str.Append(" <td align='center' class='tdClass'><a href='#' onclick=delRow('" + z + "')>删除</a></td>");
                str.Append(" <td align='center' class='tdClass'><a href='#' onclick='popDialog(\"" + model.FItemNo + "\")'>" + model.FItemName + "</a><input type='hidden' id='FItemNo' name='FItemNo' value='" + model.FItemNo + "'></td>");
                str.Append(" <td align='center' class='tdClass'>"+ model.FPrice + "</td>");
                str.Append(" <td align='center' class='tdClass'>" + model.FQcQty + "</td>");
                str.Append(" <td align='center' class='tdClass'><input type='text' id='FQty' name='FQty' onkeyup=\"this.value=this.value.replace(/[^\\d]/g,'')\" onafterpaste=\"this.value=this.value.replace(/[^\\d]/g,'')\" value='" + model.FApplyQty + "'></td>");
                //str.Append(" <td align='center' class='tdClass'><input type='text' id='FPurchaseDate' name='FPurchaseDate' value=''></td></tr>");
            }
            return str.ToString();
        }

        public string DelOfficeItemUseAppayALL(string IDList)
        {
            string str = string.Empty;
            BLL.ItemRequisitionApply ItemRequisitionApplyBll = new BLL.ItemRequisitionApply();
            try
            {
                ItemRequisitionApplyBll.DeleteList(IDList);
                str = "ok";
            }
            catch (Exception)
            {
                str = "error";
            }
            return str;
        }

        public string DelOfficeItemUseAppay(string ID)
        {
            string str = string.Empty;
            BLL.ItemRequisitionApply ItemRequisitionApplyBll = new BLL.ItemRequisitionApply();
            try
            {
                ItemRequisitionApplyBll.Delete(int.Parse(ID));
                str = "ok";
            }
            catch (Exception)
            {
                str = "error";
            }
            return str;
        }

        public string ClickShow(string itemClsNos, string z)
        {
            if (itemClsNos != "")
            {
                string[] nos = itemClsNos.Split(',');
                string noList = "";
                foreach (string no in nos)
                {
                    if (noList != "")
                    {
                        noList += ",'" + no + "'";
                    }
                    else
                    {
                        noList = "'" + no + "'";
                    }
                }
                BLL.Item ItemBLL = new BLL.Item();
                List<Model.Item> ItemList = ItemBLL.GetListAll("FItemNo in (" + noList + ")");
                List<Model.ItemRequisitionApplyEntry> ItemRequisitionApplyEntry = new List<Model.ItemRequisitionApplyEntry>();
                foreach (Model.Item model in ItemList)
                {
                    Model.ItemRequisitionApplyEntry ItemRequisitionApplyEntryModel = new Model.ItemRequisitionApplyEntry();
                    ItemRequisitionApplyEntryModel.FItemNo = model.FItemNo;
                    ItemRequisitionApplyEntryModel.FQty = 0;
                    ItemRequisitionApplyEntryModel.FItemName = model.FItemName;
                    ItemRequisitionApplyEntryModel.FPrice = model.FPrice;
                    ItemRequisitionApplyEntryModel.FQcQty = model.FQty.ToString();
                    ItemRequisitionApplyEntry.Add(ItemRequisitionApplyEntryModel);
                }
                int zs = int.Parse(z);
                return GetTable(ItemRequisitionApplyEntry, ref zs) + "|" + zs;
            }
            else
            {
                return "";
            }
        }

    }
}
